/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package se.sll.service.catalogue.cli;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.Future;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import lombok.extern.slf4j.Slf4j;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.DefaultExchange;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import se.sll.service.catalogue.common.RestClientHelper;
import se.sll.service.catalogue.common.property.CatalogProperties;
import se.sll.service.catalogue.common.rest.model.Unit;
import se.sll.service.catalogue.common.rest.request.CapacityCreateRequest;
import se.sll.service.catalogue.common.rest.request.CreateProductRequest;
import se.sll.service.catalogue.common.rest.response.HSAProcessor;
import se.sll.service.catalogue.common.rest.response.VMIdMapResponse;
import se.sll.service.catalogue.importer.extract.VMCareGiver;
import se.sll.service.catalogue.importer.extract.VTGetProcessor;
import se.sll.service.catalogue.importer.transform.ToCapacity;
import se.sll.service.catalogue.importer.transform.ToOffers;
import se.sll.service.catalogue.importer.transform.ToProducts;
import se.sll.service.catalogue.model.vm.Atgard;
import se.sll.service.catalogue.model.vm.Vantetid;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 *
 * @author khaleddaham
 */
@Slf4j
public class ImportUsers {

    private static final String REST_URL_PRODUCT = CatalogProperties.getProperty(CatalogProperties.NAME.PRODUCT_BASE_URL) + "/products/";
    private static final String REST_URL_CAPACITY = "http://localhost:8080/capacity/capacity/";
    private static final String REST_URL_OFFERS = CatalogProperties.getProperty(CatalogProperties.NAME.OFFERS_BASE_URL) + "/units/";

    private static VTGetProcessor vtGetProcessor;
    private static ToCapacity toCapacity;
    private static ToOffers toOffers;
    private static ToProducts toProducts;
    private static Document doc = null;
    Future<Object> vtGetFuture = null;
    private static DefaultCamelContext ctx = null;
    private static ProducerTemplate template = null;
    private static String CAMEL_CREATE_USERS = "gui:create:users";

    private void readVtGet(String file) {
        Future<Object> future = template.asyncRequestBody("direct:start:vtget", file);
//        String response = template.extractFutureBody(future, String.class)
    }

    private static void loadRoutes() throws Exception {
        ctx = new DefaultCamelContext();
        ctx.addRoutes(new RouteBuilder() {
            @Override
            public void configure() {
                from(CAMEL_CREATE_USERS)
                        .setHeader(Exchange.HTTP_METHOD, constant("POST"))
                        .setHeader(Exchange.CONTENT_TYPE, constant("application/json; charset=UTF-8"))
                        .setHeader(Exchange.ACCEPT_CONTENT_TYPE, constant("application/json; charset=UTF-8"))
                        .to("http://api.offentligdata.minavardkontakter.se/orgmaster-hsa/v1/hsaObjects/")
                        .bean(new HSAProcessor(), "hsaListResponseJSON")
                        .log("HSACache load finished.");
            }
        });
        ctx.start();
    }

    private Vector importExcelSheet(String fileName) {
        Vector cellVectorHolder = new Vector();
        try {
            Workbook workBook = WorkbookFactory.create(new FileInputStream(fileName));
            Sheet sheet = workBook.getSheetAt(0);
            Iterator rowIter = sheet.rowIterator();

            while (rowIter.hasNext()) {
                XSSFRow row = (XSSFRow) rowIter.next();
                Iterator cellIter = row.cellIterator();
                Vector cellStoreVector = new Vector();

                while (cellIter.hasNext()) {
                    XSSFCell cell = (XSSFCell) cellIter.next();
                    cellStoreVector.addElement(cell);
                }
                cellVectorHolder.addElement(cellStoreVector);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return cellVectorHolder;
    }

    /**
     * Standalone runner for importing data to offer/products/capacity/idmap
     *
     * @param args
     * @throws XPathExpressionException
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException, Exception {
        loadRoutes();
        template = ctx.createProducerTemplate();
        Future<Object> vtGetFuture = template.asyncRequestBody("direct:start:vtget", "file:/Users/khaleddaham/vantetider.xml");
        Map<String, Object> vtgetResponse = (Map<String, Object>) template.extractFutureBody(vtGetFuture, Object.class);

        HashMap<VMCareGiver, VMIdMapResponse> idmapResponse = (HashMap<VMCareGiver, VMIdMapResponse>) template.extractFutureBody(vtGetFuture, Object.class);
        Map<String, Object> obj = new HashMap<>();
        obj.put("capacity", vtgetResponse.get("capacity"));
        obj.put("idmap", idmapResponse);
        List<Atgard> productList = (List<Atgard>) vtgetResponse.get("product");
        List<Vantetid> capacityList = (List<Vantetid>) vtgetResponse.get("capacity");

        for (Atgard a : productList) {
            Set<String> codes = new HashSet<>();
            for (Vantetid c : capacityList) {
                if (c.getAtgard().getAtgardID().equals(a.getAtgardID()) && c.getAtgard().getAtgardTypID().equals(a.getAtgardTypID())) {
                    codes.addAll(getProductCodes(c));
                }
            }
            if (!codes.isEmpty()) {
                codes.add("7");
                codes.add("8");
            }
            a.setCodes(codes);
        }
        log.info("Adding {} products.", productList.size());
        RestClientHelper.init(REST_URL_PRODUCT);
        ToProducts toP = new ToProducts();

        template.sendBody("direct:start:capacity:add", obj);
    }

    private static Set<String> getProductCodes(Vantetid v) {
        Set<String> codes = new HashSet<>();
        // åtgärdsTyper som skall matcha väntetid 1 och 2
        List<String> reception = Arrays.asList("1");
        // åtgärdsTyper som skall matcha väntetid 3 och 4        
        List<String> examination = Arrays.asList("2");
        // åtgärdsTyper som skall matcha väntetid 5 och 6        
        List<String> operation = Arrays.asList("3", "5");
        // åtgärdstyper som skall mappas om till mottagning.
        List<String> mapToReception = Arrays.asList("4", "6");
        if (v.getVtidMottag() != null) {
            codes.add("1");
        }
        if (v.getVtidMottagFortur() != null) {
            codes.add("2");
        }
        if (v.getVtidOperationMottag() != null) {
            codes.add("3");
        }
        if (v.getVtidOperationMottagFortur() != null) {
            codes.add("4");
        }
        if (v.getVtidOperation() != null) {
            if (mapToReception.contains(v.getAtgard().getAtgardTypID())) {
                codes.add("1");
            } else {
                codes.add("5");
            }
        }
        if (v.getVtidOperationFortur() != null) {
            if (mapToReception.contains(v.getAtgard().getAtgardTypID())) {
                codes.add("2");
            }
        }
        return codes;
    }

    private static void main2() throws Exception {
        vtGetProcessor = new VTGetProcessor();
        toCapacity = new ToCapacity();
        toOffers = new ToOffers();
        toProducts = new ToProducts();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
//        doc = builder.parse("file:/Users/khaleddaham/NetBeansProjects/sll-servicecatalogue/docs/snod-vtget-example.xml");
        doc = builder.parse("file:/Users/khaleddaham/vantetider.xml");
        ctx = new DefaultCamelContext();
        Exchange inputExchange = new DefaultExchange(ctx);
        ctx.createConsumerTemplate();
        inputExchange.getIn().setBody(doc);
        Exchange exchange = null;//vtGetProcessor.process(inputExchange);

        //Exchange capacityExchange = toCapacity.process(exchange);
        Exchange offersExchange = toOffers.process(exchange);
        Exchange productsExchange = toProducts.process(exchange);

        Map map = null;//(Map) capacityExchange.getIn().getBody();
        Set<CapacityCreateRequest> restCapacities = (Set<CapacityCreateRequest>) map.get("capacity");
        Set<CreateProductRequest> restProducts = (Set<CreateProductRequest>) map.get("product");
        Set<Unit> restUnits = (Set<Unit>) map.get("offer");
        List<Vantetid> waitingTimes = (List<Vantetid>) exchange.getProperty("capacities");

        // 1 add idmap
//        for (VMIdMapCreateRequest req : getVmIdMapCreateRequestList(waitingTimes)) {
//            log.info(req.toString());
//            postVmIdmapCreate(req);
//        }
        // 2 add products
//        log.info("Adding {} products.", restProducts.size());
//        RestClientHelper.init(REST_URL_PRODUCT);
//        for (CreateProductRequest v : restProducts) {
//            log.info(v.toString());
//            RestClientHelper.sendJSONObject(v);
//        }
        // 3 add capacities
        log.info("Adding {} capacities.", restCapacities.size());
        RestClientHelper.init(REST_URL_CAPACITY);
        for (CapacityCreateRequest v : restCapacities) {
//            System.out.println(v.toString());
            if (v.getHsaID() == null) {
                continue;
            }
//            RestClientHelper.sendJSONObject(v);
        }
    }
}
